<template>
  <div class="app-container">
     <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="85px" class="globalSerchFormStyle">
      <el-row>
        <el-col :span=" 6" v-if="authUser">
          <el-form-item label="油企名称" prop="enterpriseId" size="small">
            <el-select style="width: 180px" v-model="queryParams.enterpriseId" :clearable="true" filterable placeholder="请选择油企" @change="handleSelectChange">
              <el-option v-for="(item, index) in enterpriseList" :key="index" :value="item.enterpriseId" :label="item.enterpriseName"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="油站名称" prop="stationNames" size="small">
            <el-select style="width: 180px" v-model="queryParams.stationId" :clearable="true" filterable placeholder="请选择油站名称">
              <el-option v-for="item in stationList" :key="item.stationId" :label="item.stationName" :value="item.stationId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="时间" prop="timeRange" size="small">
            <el-date-picker v-model="timeRange" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" size="small" style="width: 180px">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="订单号" prop="orderNo" size="small">
            <el-input v-model="queryParams.orderNo" placeholder="请输入订单号" clearable size="small" style="width: 180px"/>
          </el-form-item>
        </el-col>
         <el-col :span="6">
          <el-form-item label="手机号" prop="mobilePhone" size="small">
            <el-input v-model="queryParams.mobilePhone" placeholder="请输入手机号" clearable size="small" style="width: 180px"/>
          </el-form-item>
        </el-col>
         <el-col :span="6">
          <el-form-item label="渠道名称" prop="labelName" size="small">
            <el-input v-model="queryParams.labelName" placeholder="请输入渠道名称" clearable size="small" style="width: 180px"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row class="global_el_rowStyle" :gutter="10" style="  border-top: none;  border-bottom: 1px solid #f5f5f5;  margin-top: 0px;">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-search" @click="onSeach" size="mini" >搜索</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-upload" @click="onImport" size="mini" >导入</el-button >
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-edit-outline" @click="onBatchAudit" size="mini" plain >批量审核</el-button>
      </el-col>
    </el-row>
    <el-table :data="list":row-class-name="tableRowClassName" style="width: 100%" v-loading="loading" @selection-change="handleSelectionChange"  ref="multipleTable">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="序号" type="index" align="center">
        <template slot-scope="scope">
          <span>{{ (page - 1) * pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column align="left" v-if="authUser" prop="enterpriseName" label="油企名称" :show-overflow-tooltip="true"/>
      <el-table-column align="left" prop="stationName" label="油站名称" :show-overflow-tooltip="true"/>
      <el-table-column align="left" prop="labelName" label="渠道名称" :show-overflow-tooltip="true"/>
      <el-table-column align="left" prop="labelRuleType" label="类型" :show-overflow-tooltip="true"/>
      <el-table-column align="left" prop="categoryName" label="类型名称" :show-overflow-tooltip="true"/>
      <el-table-column align="left" prop="userName" label="申请人" :show-overflow-tooltip="true"/>
      <el-table-column align="left" prop="mobilePhone" label="手机号码" :show-overflow-tooltip="true"/>
      <el-table-column align="left" prop="plateNumber" label="车牌号" :show-overflow-tooltip="true"/>
       <el-table-column align="left" prop="orderNo" label="订单号" :show-overflow-tooltip="true"/>
      <el-table-column align="left" prop="attaChment" label="附件" :show-overflow-tooltip="true" >
         <template slot-scope="scope">
            <el-button type="text" size="small" :disabled="!scope.row.files" @click="onAccessory(scope.row.files)">附件</el-button>
         </template>
      </el-table-column>
      <el-table-column align="left" prop="createTime" label="申请时间" :show-overflow-tooltip="true"/>
      <el-table-column align="left" prop="status" label="状态" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{scope.row.status =='IN_REVIEW'?'审核中':scope.row.status =='PASS'?'通过':scope.row.status=='FAIL'?'审核不通过':''}}</span>
        </template>
      </el-table-column>
      <el-table-column  fixed="right" label="操作" width="100" >
      <template slot-scope="scope">
        <el-button  @click="handleOk(scope.row)" :disabled="scope.row.status!='IN_REVIEW'" type="text" size="small">同意</el-button>
        <el-button @click="handleCancel(scope.row)" :disabled="scope.row.status!='IN_REVIEW'" type="text" size="small">驳回</el-button>
      </template>
      </el-table-column>
    </el-table>

    <el-pagination class="fr" style="margin-top: 8px" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="page" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>
    <!-- 批量导入 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body style="">
      <el-upload ref="upload" :before-upload="beforeAvatarUpload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '/' + upload.labelId" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-link type="info" style="font-size: 12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="审核意见" :visible.sync="dialogVisible" width="30%">
      <el-input v-model="input_idea" type="textarea" placeholder="请输入内容" maxlength="200"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="onHandleCancel">{{isbatch?'驳回':'取消'}}</el-button>
        <el-button type="primary" @click="onConfirm">{{isbatch?'同意':'确定'}}</el-button>
      </span>
    </el-dialog>
  <el-dialog
    title="附件资料"
    :visible.sync="dialogVisible2"
    width="40%">
    <div class="img_prew" @click="dialogVisible2=false">
      <viewer :images="srcList">
        <img style="width:150px;height:150px; padding-left:20px; margin-top:50px;" v-for="src in srcList" :src="src" :key="src" class="image">
      </viewer>
      </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible2 = false">取 消</el-button>
      <el-button type="primary" @click="dialogVisible2 = false">确 定</el-button>
    </span>
  </el-dialog>
  </div>
</template>

<script>
import { enterpriseList } from "@/api/station/orderHistory";
import { listEnterpriseStation,getStationList,getStationByEnterprise, } from "@/api/dept";
import { getToken } from "@/utils/auth";
import { getListApi,actAuditApi} from "@/api/label/new-label"
import getUserProfileName from "@/utils/getUserProfile";
import 'viewerjs/dist/viewer.css'
import VueViewer from 'v-viewer'
import Vue from 'vue'
Vue.use(VueViewer)
import {
  listPersonnel,
  listEnterpriseUser,
  listQuery,
} from "@/api/station/personnel";
export default {
  name:"LabelAudit",
  data(){ 
    return{ 
      queryParams: {
        enterpriseId: "",//油企id
        stationId: "",//油站id
        stationNames: "",//油站名称
        orderNo:"",//订单号
        mobilePhone:"",//手机号
        labelName:""//渠道名称
      },
      total: 0,
      page: 1,
      pageSize: 10,
      list:[],
      timeRange: [],//时间范围
      enterpriseList: [],
      stationList: [],
      loading: false,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url:
          process.env.VUE_APP_BASE_API + "/customer/cardImport/importLabelUser",
      },
      selectionList:[],
      input_idea:'',//意见内容
      dialogVisible:false,
      params:{},//单个点击同意或者驳回的参数
      isbatch:false,//是否批量
      multipleSelection: [] ,
      dialogVisible2:false,
      srcList:[]
    }
  },
  computed: {
    authUser() {
      let roles = this.$store.state.user.roles;
      if (roles.includes("admin")) {
        return true;
      } else {
        return false;
      }
    },
  },
  created(){
    this.getEnterpriseList();
    this.getData()
    this.getPersonnelList()
    // 如果当前是油企账号，则获取该企业下的油站
    if (this.presentEnterprise && this.presentEnterprise.enterpriseId) {
      console.log("是油企账号")
      this.getStationList(this.presentEnterprise.enterpriseId);
    } else {
      console.log("不是油企账号")
      this.getStationList();
    }
  },
  methods:{ 
    // 查询油企
    getEnterpriseList() {
      enterpriseList().then((res) => {
        this.enterpriseList = res.rows;
      });
    },
    getPersonnelList() {
      let userLevelIs = this.$store.state.user.userLevel;
      if (["5", "6"].includes(userLevelIs)) {
        listEnterpriseUser().then((res) => {
          this.personnelList = res;
        });
      } else {
        let data = { data: null };
        let userLevel = this.$store.state.user.userLevel;
        if (userLevel === "0") {
          console.log("111admin账号");
        } else if (userLevel === "1") {
          data = {
            enterpriseId:
              this.presentEnterprise && this.presentEnterprise.enterpriseId,
          };
        } else if (userLevel === "2") {
          data = {
            enterpriseId:
              this.presentEnterprise && this.presentEnterprise.enterpriseId,
            stationId: this.$store.state.user.stationId,
          };
        } else {
          console.log("111admin账号");
        }
        listQuery(data).then((res) => {
          this.personnelList = res.rows;
        });
      }
    },
    // 根据油企获取该油企下的油站
    handleSelectChange(enterpriseId) {
      this.stationList = [];
      this.queryParams.stationId = null;
      this.queryParams.stationNames = null;
      this.getStationList(enterpriseId);
    },
    async getStationList(val) {
      // 判断是不是admin账号
      const isDelete = await getUserProfileName();
      if (isDelete) {
        // 是
        listEnterpriseStation({ enterpriseId: val }).then((res) => {
          console.log("是admin账号,油站名称", res);
          this.stationList = res;
        });
      } else {
        // 不是
        const res = await getStationByEnterprise();
        console.log("不是admin账号,油站名称", res);
        this.stationList = res.data;
      }
    },
    // 搜索
    onSeach(){
      this.getData()
    },
    // 导入
    onImport(){
       this.upload.title = "批量导入";
       this.upload.open = true;
    },
    // 批量审核
    onBatchAudit(){
      if(this.selectionList.length){ 
        this.dialogVisible=true
        this.isbatch=true
      }else{ 
        this.$message.warning('请选择您要审核的数据！')
      }
    },
    // 附件
    onAccessory(url){
      if(url){ 
        const filesList=url.split(',')
        this.dialogVisible2=true
        this.srcList=filesList||[]
      }else{ 
        this.$message.warning('暂无附件文件')
      }
      
    },
    // 上传表格组件的校验
    beforeAvatarUpload(file) {
      const extension = file.name.split(".").pop().toLowerCase();
      if (extension !== "xls" && extension !== "xlsx") {
        this.$message.error("仅允许导入“xls”或“xlsx”格式文件！");
        return false;
      }
      return true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
    },
    // 下载模板
    async importTemplate() {
      let res = await request.get("/customer/cardImport/labelUserTemplate", {
        responseType: "blob",
        withCredentials: false,
      });
      const fileExt = "xlsx";
      const filename = "导入模版" + (fileExt ? "." + fileExt : "");
      const blob = new Blob([res]);
      var downloadElement = document.createElement("a");
      var href = window.URL.createObjectURL(blob);
      downloadElement.href = href;
      downloadElement.download = filename;
      document.body.appendChild(downloadElement);
      downloadElement.click();
      document.body.removeChild(downloadElement);
      window.URL.revokeObjectURL(href);
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 批量选择
    handleSelectionChange(selection) {
      this.multipleSelection=selection
      if (this.multipleSelection!=0) {
      let filetr='IN_REVIEW'
       this.multipleSelection.forEach(item=>{ 
        if(item.status!=filetr){ 
          this.$refs.multipleTable.toggleRowSelection(this.list[item.index])
        }
       })
      }
      this.selectionList=this.multipleSelection.filter(item=>item.status=='IN_REVIEW')
    },
    tableRowClassName({row, rowIndex}) {
      row.index = rowIndex
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.getData()
    },
    handleCurrentChange(page) {
      this.page = page;
      this.getData()
    },
    // 同意
    handleOk(scope,row){
      this.isbatch=false
      this.selectionList=[]
      this.dialogVisible=true
      this.params={
        ids:[scope.id],
        status:'PASS' ,
       }
    },
    // 驳回
    handleCancel(scope,row){
      this.dialogVisible=true
      this.isbatch=false
      this.selectionList=[]
      this.params={
        ids:[scope.id],
        status:'FAIL' ,
       }
    },
    // 审核接口
    async actAudit(params){
      console.log('params',params);
      const res=await actAuditApi(params)
      if(res&&res.code==200){ 
        if(params.status=='FAIL'){ 
          this.$message.success('驳回成功')
        }else if(params.status=='PASS'){ 
          this.$message.success('审核成功')
        }
        this.getData()
      }else{ 
        this.$message.fail(res&&res.msg)
      }
    },
    onConfirm(type){
      let typeName=null
      if(type=='FAIL'){
        typeName='FAIL'
      }else{ 
        typeName='PASS'
      }
      let ids=[]
      if(this.isbatch){ 
        if(this.selectionList.length){ 
        this.selectionList.forEach(item=>{ 
          ids.push(item.id)
        })
        const params={
          ids:ids,
          status:typeName,
          auditOpinion:this.input_idea
        }
        this.actAudit(params)
        }
      }else{ 
        this.params.auditOpinion=this.input_idea
        this.actAudit(this.params)
      }
      this.$refs.multipleTable.clearSelection();
      this.selectionList=[]
      this.params={}
      this.input_idea=''
      this.dialogVisible=false
    },
    onHandleCancel(){ 
      if(this.isbatch){ 
        this.onConfirm('FAIL')
      }else{ 
        this.dialogVisible=false
        this.input_idea=''
        this.$refs.multipleTable.clearSelection();
        this.selectionList=[]
      }
      
    },
    // 获取数据
    getData() {
      if (this.loading) return;
      this.loading = true;
      this.queryParams.page=this.page
      this.queryParams.size=this.pageSize
      this.queryParams['startTime']=this.timeRange? this.timeRange[0]:null
      this.queryParams['endTime']=this.timeRange?this.timeRange[1]:null
      getListApi(this.queryParams).then((res) => {
        if (res && res.content) {
          this.list=res.content||[]
          this.total = res.totalElements||0;
        } else {
          this.list = [];
          this.total = 0;
          this.$message.error(res.msg);
        }
        
      });
      this.loading = false;
    },
  }
}
</script>

<style scoped>
.img_prew{ 
  width: 100%;
  display: flex;
  justify-content: space-between;
}
</style>